package com.javabi.common.management.bean;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javabi.common.lang.clazz.ClassResolver;

public class BeanAttribute implements IBeanAttribute {

	private static final Logger log = LoggerFactory.getLogger(BeanAttribute.class);

	private final IBean bean;
	private final MBeanAttributeInfo attribute;

	public BeanAttribute(IBean bean, MBeanAttributeInfo attribute) {
		this.bean = bean;
		this.attribute = attribute;
	}

	@Override
	public String getName() {
		return attribute.getName();
	}

	@Override
	public Class<?> getType() {
		return new ClassResolver().resolveClass(attribute.getType());
	}

	@Override
	public Object getValue() {
		try {
			MBeanServer server = bean.getServer();
			ObjectName name = bean.getObjectName();
			return server.getAttribute(name, getName());
		} catch (Exception e) {
			log.error("Failed to get value for attribute: " + getName() + ", bean: " + bean.getName(), e);
			return e.getClass().getSimpleName();
		}
	}

	@Override
	public int compareTo(IBeanAttribute compare) {
		return getName().compareTo(compare.getName());
	}

	@Override
	public IBean getBean() {
		return bean;
	}

}
